package org.qiaice.interceptor;

import io.jsonwebtoken.Claims;
import jakarta.annotation.Nonnull;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.qiaice.context.BaseContext;
import org.qiaice.result.Result;
import org.qiaice.util.JsonUtil;
import org.qiaice.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class TokenAuthorizationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(
            @Nonnull HttpServletRequest request, @Nonnull HttpServletResponse response,
            @Nonnull Object handler
    ) {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String value = request.getHeader("Token");
        if (!StringUtils.hasText(value)) {
            JsonUtil.write(response, Result.no("未携带 token"));
            return false;
        }
        try {
            Claims payload = TokenUtil.parseToken(value).getPayload();
            BaseContext.setContext(payload);
            log.info("当前员工 id: {}, 用户名: {}",
                    payload.get("id", Long.class),
                    payload.get("username", String.class));
        } catch (RuntimeException e) {
            JsonUtil.write(response, Result.no(e.getMessage()));
            return false;
        }
        return true;
    }
}
